package com.university.evaluation.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.university.evaluation.common.ResponseResult;
import com.university.evaluation.domain.dto.RoleDTO;
import com.university.evaluation.entity.Role;
import com.university.evaluation.entity.User;
import com.university.evaluation.mapper.RoleMapper;
import com.university.evaluation.mapper.UserMapper;
import com.university.evaluation.service.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<Role> getRolesByStatus(Integer status) {
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", status);
        return list(queryWrapper);
    }

    @Override
    public boolean batchDeleteRoles(List<Long> roleIds) {
        // 先检查这些角色是否被使用
        for (Long roleId : roleIds) {
            if (isRoleUsed(roleId)) {
                // 如果有角色被使用，则不进行批量删除
                return false;
            }
        }
        return removeByIds(roleIds);
    }

    @Override
    public boolean isRoleUsed(Long roleId) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id", roleId);
        return userMapper.selectCount(queryWrapper) > 0;
    }

    @Override
    public Role getRoleByKey(String roleKey) {
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_key", roleKey);
        return getOne(queryWrapper);
    }

    @Override
    public ResponseResult<?> getAllRoles() {
        try {
            List<Role> roles = list();
            return ResponseResult.success("获取成功", roles);
        } catch (Exception e) {
            log.error("获取所有角色列表失败", e);
            return ResponseResult.failure("获取失败");
        }
    }

    @Override
    public ResponseResult<?> getRoleById(Long roleId) {
        try {
            Role role = getById(roleId);
            if (role != null) {
                return ResponseResult.success("获取成功", role);
            } else {
                return ResponseResult.failure("角色不存在");
            }
        } catch (Exception e) {
            log.error("获取角色详情失败", e);
            return ResponseResult.failure("获取失败");
        }
    }

    @Override
    @Transactional
    public ResponseResult<?> createRole(RoleDTO roleDTO) {
        try {
            Role role = new Role();
            BeanUtils.copyProperties(roleDTO, role);
            role.setStatus(1); // 默认启用
            
            boolean success = save(role);
            if (success) {
                return ResponseResult.success("创建成功", role);
            } else {
                return ResponseResult.failure("创建失败");
            }
        } catch (Exception e) {
            log.error("创建角色失败", e);
            return ResponseResult.failure("创建失败");
        }
    }

    @Override
    @Transactional
    public ResponseResult<?> updateRole(Long roleId, RoleDTO roleDTO) {
        try {
            Role role = getById(roleId);
            if (role == null) {
                return ResponseResult.failure("角色不存在");
            }
            
            BeanUtils.copyProperties(roleDTO, role, "id");
            
            boolean success = updateById(role);
            if (success) {
                return ResponseResult.success("更新成功");
            } else {
                return ResponseResult.failure("更新失败");
            }
        } catch (Exception e) {
            log.error("更新角色失败", e);
            return ResponseResult.failure("更新失败");
        }
    }

    @Override
    @Transactional
    public ResponseResult<?> deleteRole(Long roleId) {
        try {
            if (isRoleUsed(roleId)) {
                return ResponseResult.failure("角色正在使用中，无法删除");
            }
            
            boolean success = removeById(roleId);
            if (success) {
                return ResponseResult.success("删除成功");
            } else {
                return ResponseResult.failure("删除失败");
            }
        } catch (Exception e) {
            log.error("删除角色失败", e);
            return ResponseResult.failure("删除失败");
        }
    }

    @Override
    public ResponseResult<?> getRolePermissions(Long roleId) {
        try {
            // 这里需要根据实际的权限表结构来实现
            // 目前返回空列表
            return ResponseResult.success("获取成功", List.of());
        } catch (Exception e) {
            log.error("获取角色权限失败", e);
            return ResponseResult.failure("获取失败");
        }
    }

    @Override
    @Transactional
    public ResponseResult<?> updateRolePermissions(Long roleId, Long[] permissionIds) {
        try {
            // 这里需要根据实际的权限表结构来实现
            // 目前返回成功
            return ResponseResult.success("更新成功");
        } catch (Exception e) {
            log.error("更新角色权限失败", e);
            return ResponseResult.failure("更新失败");
        }
    }

    @Override
    public ResponseResult<?> getRolePageList(Map<String, Object> params) {
        try {
            int pageNum = Integer.parseInt(params.getOrDefault("pageNum", "1").toString());
            int pageSize = Integer.parseInt(params.getOrDefault("pageSize", "10").toString());
            
            Page<Role> page = new Page<>(pageNum, pageSize);
            QueryWrapper<Role> wrapper = new QueryWrapper<>();
            
            // 根据参数添加查询条件
            if (params.containsKey("roleName")) {
                wrapper.like("role_name", params.get("roleName").toString());
            }
            if (params.containsKey("status")) {
                wrapper.eq("status", params.get("status"));
            }
            
            wrapper.orderByDesc("create_time");
            page = page(page, wrapper);
            
            Map<String, Object> result = new HashMap<>();
            result.put("list", page.getRecords());
            result.put("total", page.getTotal());
            result.put("pageNum", pageNum);
            result.put("pageSize", pageSize);
            result.put("pages", page.getPages());
            
            return ResponseResult.success("获取成功", result);
        } catch (Exception e) {
            log.error("获取角色分页列表失败", e);
            return ResponseResult.failure("获取失败");
        }
    }

    @Override
    public ResponseResult<?> getUserRoles(Long userId) {
        try {
            // 这里需要根据实际的用户角色关系表来实现
            // 目前返回空列表
            return ResponseResult.success("获取成功", List.of());
        } catch (Exception e) {
            log.error("获取用户角色失败", e);
            return ResponseResult.failure("获取失败");
        }
    }

    @Override
    @Transactional
    public ResponseResult<?> updateUserRoles(Long userId, Long[] roleIds) {
        try {
            // 这里需要根据实际的用户角色关系表来实现
            // 目前返回成功
            return ResponseResult.success("更新成功");
        } catch (Exception e) {
            log.error("更新用户角色失败", e);
            return ResponseResult.failure("更新失败");
        }
    }

}